package com.study.controller;

import com.study.dto.UserDto;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileUploadController {

    /**
     * 多文件上传
     */
    @PostMapping("/multi")
    @SuppressWarnings("all")
    public Object importMd(@RequestParam("files") MultipartFile[] files) {

        String basePath = "E:\\TEST";

        int total = 0;
        int success = 0;
        int fail = 0;
        for (MultipartFile file : files) {
            total++;
            File dir = new File(basePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file1 = new File(basePath + "\\" + file.getOriginalFilename());
            try {
                file.transferTo(file1);
                success++;
                System.out.println("第 " + total + " 个文件成功，文件名：" + file.getOriginalFilename());
            } catch (IOException e) {
                fail++;
                System.out.println("第 " + total + " 个文件失败，文件名：" + file.getOriginalFilename());
                e.printStackTrace();
            }
        }
        HashMap<String, Integer> map = new HashMap<>(4);
        map.put("total", total);
        map.put("success", success);
        map.put("fail", fail);
        return map;
    }

    /**
     * HttpServletRequest 统一接收字段和文件数据
     */
    @PostMapping("/test")
    public String test(HttpServletRequest request) throws IOException {
        if (request instanceof MultipartHttpServletRequest) {

            // HttpServletRequest ==> MultipartHttpServletRequest
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;

            // 通过 key 获取指定的文件
            MultipartFile headImgFile = mreq.getFile("headImg");
            // 文件是否为空
            boolean empty = headImgFile.isEmpty();
            // 获取字节数组
            byte[] bytes = headImgFile.getBytes();
            // 文件名, 包括文件扩展名
            String originalFilename = headImgFile.getOriginalFilename();
            // 文件对应 key, 即 headImg
            String fileName = headImgFile.getName();

            // 文件大小, 字节
            long size = headImgFile.getSize();
            // kb
            double v = (double) size / 1024.00;

            // 文件复制到本地磁盘(文件不存在会自动创建)
            File file1 = new File("F:/headImg.jpg");
            headImgFile.transferTo(file1);

            // 获取所有文件, 不需要知道 key
            Map<String, MultipartFile> fileMap = mreq.getFileMap();
            fileMap.keySet().forEach((item) -> {
                MultipartFile file = fileMap.get(item);
            });

            // 字段
            String username = request.getParameter("username");
            String id = request.getParameter("id");

            return "success";
        }
        return "error";
    }


    /**
     * 和上面的区别是: 如果是 swagger 能直观看到请求参数
     * 1. 文件的 key 是 file
     * 2. dot 不能使用 @RequestBody 注解
     */
    @PostMapping("/test2")
    public String test2(UserDto dto, MultipartFile file) {
        return "上传成功";
    }


    /**
     * 文件下载, 返回流
     */
    @GetMapping("/test3")
    public HttpServletResponse test3(HttpServletResponse response) throws IOException {

        File file = new File("F:\\1原型\\错题集模板.xlsx");

        String fileName = file.getName();

        InputStream is = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        is.close();

        // 清空response
        response.reset();

        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=\"错题集" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1) + "\"");
        response.addHeader("Content-Length", "" + file.length());
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        os.write(buffer);
        os.flush();
        os.close();

        return response;
    }

    /**
     * 下载本地文件
     */
    @GetMapping("/test4")
    public void test4(HttpServletResponse response) throws FileNotFoundException, UnsupportedEncodingException {

        // 保存的文件名
        String fileName = "下载的文件.xlsx";
        // 中文
        fileName = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);

        // 需要下载的文件
        InputStream inStream = new FileInputStream("F:\\1原型\\错题集模板.xlsx");

        // 设置输出的格式
        response.reset();
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
